package com.apes.fn.business.carAccident.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.business.carAccident.modle.ClaimWorkOrder;
import com.apes.fn.business.carAccident.modle.WorkOrderOperationRecord;
import com.apes.fn.business.carAccident.repository.ClaimWorkOrderRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName ClaimWorkOrderService
 * @Author wsj
 * @Date 2021/6/6 16:35
 * @description 定损工单业务层
 */
@Service("claimWorkOrderService")
public class ClaimWorkOrderService extends DomainService {
    @Autowired
    private ClaimWorkOrderRepository orderRepository;


    /**
     * 功能：完成代勘
     *
     * @param request
     * @return
     */
    public ClaimWorkOrder finish(SimpleRequest request) {
        ClaimWorkOrder claimWorkOrder = request.getO(ClaimWorkOrder.class);
        claimWorkOrder = insertOperationRecord(request, claimWorkOrder, "完成代勘","");
        claimWorkOrder.setState("finish");
        claimWorkOrder = orderRepository.saveAndFlush(claimWorkOrder);
        return  claimWorkOrder;
    }

    /**
     * 功能：新增
     *
     * @param request
     * @return
     */
    public ClaimWorkOrder save(SimpleRequest request) {
        ClaimWorkOrder claimWorkOrder = request.getO(ClaimWorkOrder.class);
        claimWorkOrder.setState("create");
        claimWorkOrder = orderRepository.saveAndFlush(claimWorkOrder);
        return  claimWorkOrder;
    }

    /**
     * 功能：终止代勘
     *
     * @param request
     * @return
     */
    public ClaimWorkOrder repeal(SimpleRequest request) {
        ClaimWorkOrder claimWorkOrder = request.getO(ClaimWorkOrder.class);
        claimWorkOrder = insertOperationRecord(request, claimWorkOrder, "终止代勘","");
        claimWorkOrder.setState("repeal");
        claimWorkOrder = orderRepository.saveAndFlush(claimWorkOrder);
        return claimWorkOrder;
    }

    /**
     * 功能：拒绝接单
     *
     * @param request
     * @return
     */
    public Map refuse(SimpleRequest request) {
        JSONObject param = request.getJO();
        String remark = param.getString("remark");
        ClaimWorkOrder claimWorkOrder = checkData(param);
        claimWorkOrder = insertOperationRecord(request, claimWorkOrder, "拒绝接单",remark);
        claimWorkOrder.setState("repeal");
        claimWorkOrder = orderRepository.saveAndFlush(claimWorkOrder);
        return  MapUtil.mapper("id",claimWorkOrder.getId());
    }

    /**
     * 功能：确认接单
     *
     * @param request
     * @return
     */
    public Map accept(SimpleRequest request) {
        JSONObject param = request.getJO();
        ClaimWorkOrder claimWorkOrder = checkData(param);
        claimWorkOrder.setState("accept");
        claimWorkOrder = insertOperationRecord(request, claimWorkOrder, "确认接单","");
        claimWorkOrder = orderRepository.saveAndFlush(claimWorkOrder);
        return  MapUtil.mapper("id",claimWorkOrder.getId());
    }

    /**
     * 功能：无法勘察
     *
     * @param request
     * @return
     */
    public Map goBack(SimpleRequest request) {
        JSONObject param = request.getJO();
        String remark = param.getString("remark");
        ClaimWorkOrder claimWorkOrder = checkData(param);
        claimWorkOrder.setState("goBack");
        claimWorkOrder = insertOperationRecord(request, claimWorkOrder, "无法勘察", remark);
        claimWorkOrder = orderRepository.saveAndFlush(claimWorkOrder);
        return  MapUtil.mapper("id",claimWorkOrder.getId());
    }

    /**
     * 功能：完成勘察
     *
     * @param request
     * @return
     */
    public Map complete(SimpleRequest request) {
        JSONObject param = request.getJO();
        String remark = param.getString("remark");
        ClaimWorkOrder claimWorkOrder = checkData(param);
        claimWorkOrder.setState("finish");
        claimWorkOrder = insertOperationRecord(request, claimWorkOrder, "完成勘察",remark);
        claimWorkOrder = orderRepository.saveAndFlush(claimWorkOrder);
        return  MapUtil.mapper("id",claimWorkOrder.getId());
    }

    /**
     * 功能：工单转门店
     *
     * @param request
     * @return
     */
    public ClaimWorkOrder toStore(SimpleRequest request) {
        ClaimWorkOrder claimWorkOrder = request.getO(ClaimWorkOrder.class);
        claimWorkOrder.setState("新增");
        claimWorkOrder = orderRepository.saveAndFlush(claimWorkOrder);
        return  claimWorkOrder;
    }

    private ClaimWorkOrder  checkData (JSONObject param) {
        String id = param.getString("id");
        int version = param.getInteger("version");
        ClaimWorkOrder workOrder = orderRepository.findOne(id);
        if (Objects.isNull(workOrder)) {
            throw new RuntimeException("未找到对应定损工单,单号: "+ id);
        }
        if (version != workOrder.getVersion()) {
            throw new RuntimeException("数据发生改变,请刷新重试!!!");
        }
        workOrder.setVersion(version);
        return workOrder;
    }
    /**
     * 功能：修改代勘人
     *
     * @param request
     * @return
     */
    public Map updatePersonnel(SimpleRequest request) {
        JSONObject param = request.getJO();
        String personId = param.getString("person");
        ClaimWorkOrder workOrder = checkData(param);
        PartyRole person = SpringManager.getBean(PartyRoleRepository.class).findOne(personId);
        if (Objects.isNull(person)) {
            throw new RuntimeException("未找到对应人员,编码: " + personId);
        }
        workOrder.setStoreStaff(person);
        workOrder.setStoreStaffName(person.getName());
        workOrder = insertOperationRecord(request, workOrder,"修改代勘人员","");
        workOrder = orderRepository.saveAndFlush(workOrder);
        return  MapUtil.mapper("id",workOrder.getId());
    }

    /**
     * 插入操作记录
     * @param request 当前会话消息
     * @param workOrder 定损工单
     * @param operationType 操作类型
     * @param remark 操作备注
     * @return
     */
    public ClaimWorkOrder insertOperationRecord(SimpleRequest request, ClaimWorkOrder workOrder,String operationType,String remark) {
        WorkOrderOperationRecord record = new WorkOrderOperationRecord();
        record.setId(SpringManager.getBean(SequenceService.class).getId(WorkOrderOperationRecord.CONST_TABLE_NAME));
        record.setOperationType(operationType);
        if (Objects.isNull(request.getPerson())) {
            record.setOperatorName("后台自动生成");
        }else {
            record.setOperator(request.getPerson());
            record.setOperatorName(record.getOperator().getName());
        }
        record.setDept(workOrder.getDept());
        record.setClaimWorkOrder(workOrder);
        record.setOperationDate(new Date());
        if (Objects.nonNull(remark)) {
            record.setRemark(remark);
        }
        workOrder.getOperationRecords().add(record);
        return workOrder;
    }

    /**
     * 功能：统计该门店多少进行中的定损工单
     *
     * @param request
     * @return
     */
    public Map countValid(SimpleRequest request) {
        JSONObject json = request.getJO();
        String paramName = "dept";
        if (!json.containsKey(paramName) || StringUtils.isEmpty(json.getString(paramName))) {
            throw new RuntimeException("门店不能为空!!!");
        }
        int number = orderRepository.countValidForDept(json.getString(paramName));
        return MapUtil.mapper("name","报案代勘","number",number);
    }

    /**
     * 功能：获取该门店多少进行中的定损工单数据
     *
     * @param request
     * @return
     */
    public List<Map<String, Object>> getClaimWorkOrderForStore(SimpleRequest request) {
        JSONObject json = request.getJO();
        String paramName = "dept";
        if (!json.containsKey(paramName) || StringUtils.isEmpty(json.getString(paramName))) {
            throw new RuntimeException("门店不能为空!!!");
        }
        return  orderRepository.getClaimWorkOrderForStore(json.getString(paramName));

    }

    /**
     * 功能：获取对应定损工单的数据
     *
     * @param request
     * @return
     */
    public JSONObject getClaimWorkOrderById(SimpleRequest request) {
        JSONObject json = request.getJO();
        JSONObject result = new JSONObject();
        JSONObject secondPart = new JSONObject();
        String paramName = "id";
        if (!json.containsKey(paramName) || StringUtils.isEmpty(json.getString(paramName))) {
            throw new RuntimeException("单号不能为空!!!");
        }
        ClaimWorkOrder workOrder = orderRepository.findOne(json.getString("id"));
        if (Objects.isNull(workOrder)) {
            throw new RuntimeException("未找到定损工单数据,单号: "+json.getString("id"));
        }
        result.put("carLicense", workOrder.getCarLicense());
        result.put("id", workOrder.getId());
        result.put("version", workOrder.getVersion());
        String state = workOrder.getState();
        result.put("state", state);
        switch (state) {
            case "create":
                result.put("stateName", "新增");
                break;
            case "accept":
                result.put("stateName", "接受代勘");
                break;
            case "finish":
                result.put("stateName", "完成代勘");
                break;
            case "goBack":
                result.put("stateName", "退回代勘");
                break;
            default:
                throw new RuntimeException("没有对应值!!!");
        }

        Map<String, String> map = orderRepository.getCarAccidentInfoById(workOrder.getSourceFrom());
        result.put("firstPart", map);
        secondPart.put("dept", workOrder.getDept().getName());
        secondPart.put("storeStaffName", workOrder.getStoreStaffName());
        secondPart.put("date", workOrder.getCreateDate());
        result.put("secondPart", secondPart);
        List<Map> list = workOrder.getOperationRecords().stream().map(
                item -> {
                    JSONObject object = new JSONObject();
                    object.put("date", item.getOperationDate());
                    object.put("operator", item.getOperatorName());
                    object.put("operationType", item.getOperationType());
                    return object;
                }
        ).collect(Collectors.toList());
        result.put("thirdPart", list);
        return result;
    }
}
